package com.ui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.UIManager;

import net.ledticker.LedTicker;
import net.ledticker.LedTickerFactory;

import org.swixml.SwingEngine;

import com.Ticker.elements.TextTickerElement;
import com.engine.DVDMovie;
import com.engine.DVDPanel;
import com.engine.IRecv;
import com.engine.ImagePanel;
import com.engine.LCDEngine;
import com.engine.ReadConfig;
import com.engine.VideoPanel;

public class LCDSQ extends JFrame implements KeyListener,IRecv,WindowListener{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JFrame frame;
	private JPanel media;
	private Map<String,TextTickerElement> elements = new HashMap<String,TextTickerElement>();
	private LedTicker ledTicker;
	private JPanel ticker;
	private boolean isAlive=true;
	private Dimension screen=Toolkit.getDefaultToolkit().getScreenSize();
	private LCDEngine lcdEng;
	private boolean m_isStop=false;
	/** The visual component (if any) */
	Component visualComponent = null;

    /** The default control component (if any) */
	Component controlComponent = null;
	Color gridColor = new Color(0x111111);
	Color bgColor =new Color(0x333333);
	private JLabel date;
	//private JLabel date1;
	private JLabel counter1,counter2,counter3,counter4,counter5,counter6,counter7,counter8,counter9,counter10;
	private JLabel nomor1,nomor2,nomor3,nomor4,nomor5,nomor6,nomor7,nomor8,nomor9,nomor10;
	
	private JLabel kurs1,kurs2,kurs3,kurs4,kurs5,kurs6,kurs7,kurs8;
	private JLabel sell1,sell2,sell3,sell4,sell5,sell6,sell7,sell8;
	private JLabel buy1,buy2,buy3,buy4,buy5,buy6,buy7,buy8;
	
	private JLabel bln1,bln2,bln3,bln4;
	private JLabel bln1usd,bln2usd,bln3usd,bln4usd;
	
	private JLabel tabungan1,tabungan1_1,idtabungan1;
	private JLabel tabungan2,tabungan2_1,idtabungan2;
	private JLabel tabungan3,tabungan3_1,idtabungan3;
	private JLabel tabungan4,tabungan4_1,idtabungan4;
	private JLabel tabungan5,tabungan5_1,idtabungan5;
	
	private JLabel tabunganusd,tabunganusd_1;
	private JLabel tabunganku,tabunganku_1;
	
	private JLabel idbln1,idbln2,idbln3,idbln4;
	public static IRecv App;
	private JPanel vp;
	private JPanel pp;
	private String marqueeText;
	public LCDSQ() throws Exception
	{
		SwingEngine  swix= new SwingEngine( this );
	    swix.render( "xml/lcdsq.xml" );
	    init();
	    frame.setUndecorated(true);
	    frame.setVisible( true );
	    frame.addKeyListener(this);
	    frame.addWindowListener(this);
	    setMaxSize();
	    
	    if(ReadConfig.GET("RUNNING_TEXTMODE").equals("LED"))
	    {
		    createLedTickerComponent();
		    ledTicker.startAnimation();
		    ticker.add(ledTicker.getTickerComponent(),BorderLayout.CENTER);
	    }
	    else
	    {
	    	String content = ReadConfig.GET("LED_TEXT");
	    	marqueeText=content;
	    	final JLabel textOutput = new JLabel( content,JLabel.LEFT);
	    	//textOutput.setOpaque(true);
	    	//textOutput.setBackground(Color.BLACK);
	    	String[] fonts = ReadConfig.GET("RUNNING_TEXTFONT").split("\\-");
	    	int style=Font.PLAIN;
	    	if(fonts[1].equals("BOLD"))
	    		style = Font.BOLD;
	    	else if(fonts[1].equals("ITALIC"))
	    		style = Font.ITALIC;
	    	int size = Integer.parseInt(fonts[2]);
	    	textOutput.setFont(new Font(fonts[0],style,size));
	    	
	    	int runningtextSleep = Integer.parseInt(ReadConfig.GET("RUNNING_TEXTSLEEP"));
	    	Timer marquee = new Timer( runningtextSleep,
					new ActionListener() {
						public void actionPerformed( ActionEvent e ) {
							char firstChar  = marqueeText.charAt( 0 );
							marqueeText = marqueeText.substring( 1, marqueeText.length() ) + firstChar;
							textOutput.setText( marqueeText);
						}
					} );
	    	
	    	String [] arrSize=ReadConfig.GET("RUNNING_TEXTSIZE").split("\\,");
	    	textOutput.setPreferredSize(new Dimension(Integer.parseInt(arrSize[0]),Integer.parseInt(arrSize[1])));
	    	textOutput.setHorizontalAlignment(SwingConstants.LEFT);
	    	String[] strColor = ReadConfig.GET("LED_COLOR").split("\\,");
		    gridColor = new Color(Integer.parseInt(strColor[0]),Integer.parseInt(strColor[1]),Integer.parseInt(strColor[2]));
	    	ticker.setBackground(gridColor);
	    	//ticker.setBorder(new EmptyBorder(-3, -160, 0, 0));
	    	ticker.add(textOutput);
	    	marquee.start();
	    }
	    //new Thread(this).start();
	    new Thread(new TimerTask()).start();
	    //start to listening on socket
	    lcdEng=new LCDEngine();
	    new Thread(lcdEng).start();
	    App=this;
	    
	    new SukuBungaThread().start();
	    new KursThread().start();
	    //new DemoThread().start();
	    showOnScreen( 1);
	}
	
	public void showOnScreen( int screen)
	{
	    GraphicsEnvironment ge = GraphicsEnvironment
	        .getLocalGraphicsEnvironment();
	    GraphicsDevice[] gs = ge.getScreenDevices();
	    if( screen > -1 && screen < gs.length )
	    {
	    	Rectangle bounds = gs[screen].getDefaultConfiguration().getBounds();
	    	frame.setSize(new Dimension(bounds.width,bounds.height));
	    	frame.setLocation(Toolkit.getDefaultToolkit().getScreenSize().width,0);
	    }
	    else if( gs.length > 0 )
	    {
	        gs[0].setFullScreenWindow( frame );
	    }
	    else
	    {
	        throw new RuntimeException( "No Screens Found" );
	    }
	}
	
	/*
	class DemoThread extends Thread
	{
		public DemoThread()
		{
			
		}
		
		public void run()
		{
			while(true)
			{
				try {
					Thread.sleep(15000L);
					//Demo.showDemo();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					//e.printStackTrace();
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					//e.printStackTrace();
				} catch (InstantiationException e) {
					// TODO Auto-generated catch block
					//e.printStackTrace();
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					//e.printStackTrace();
				} catch (UnsupportedLookAndFeelException e) {
					/// TODO Auto-generated catch block
					//e.printStackTrace();
				}
			}
		}
	}
	*/
	private void setMaxSize()
	{
		Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
		frame.setPreferredSize(dim);
		frame.setExtendedState(MAXIMIZED_BOTH);
	}
	
		/**
	   * Creates the LedTicker.
	   */
	private void createLedTickerComponent() {
	    //STEP1 : create the component
	    ledTicker = LedTickerFactory.createLedTicker();
	    int iValue = ReadConfig.toInt("LED_ELEMENT_GAP");
	    ledTicker.setElementGap(iValue);
	    iValue = ReadConfig.toInt("LED_TOKEN_GAP");
	    ledTicker.setTokenGap(10);
	    String strValue = ReadConfig.GET("LED_DOT_SIZE");
	    String[] arrValue= strValue.split("\\,");
	    ledTicker.setDotSize(Integer.parseInt(arrValue[0]),Integer.parseInt(arrValue[1]));
	    ledTicker.setDotGaps(0, 0);
	    ledTicker.setBackgroundColor(frame.getBackground());
	    String[] strColor = ReadConfig.GET("LED_COLOR").split("\\,");
	    gridColor = new Color(Integer.parseInt(strColor[0]),Integer.parseInt(strColor[1]),Integer.parseInt(strColor[2]));
	    ledTicker.setDotOffColor(gridColor);
	    iValue = ReadConfig.toInt("LED_HEIGHT");
	    ledTicker.getTickerComponent().setBounds(0,screen.height,screen.width,iValue);
	    ledTicker.getTickerComponent().setPreferredSize(new Dimension(screen.width,iValue));
	    TextTickerElement ste = new TextTickerElement(ReadConfig.GET("LED_TEXT"));
	    elements.put("1",ste);
	    ledTicker.addElement(ste);
	  }
	
	JLabel logo;
	int media_video=1;
	private void init()
	{
		logo.setIcon(new ImageIcon("images/logo_upper_left.png"));
		logo.setOpaque(true);
		logo.setBackground(Color.LIGHT_GRAY);
		showTime();
		//Font f = new Font("Tahoma",Font.BOLD,16);
		//date.setFont(f);
		//date.setForeground(Color.RED);
		//date1.setFont(f);
		//date1.setForeground(Color.RED);
		
		counter1.setHorizontalAlignment(SwingConstants.CENTER);
		//nomor1.setHorizontalAlignment(SwingConstants.CENTER);
		
		counter2.setHorizontalAlignment(SwingConstants.CENTER);
		//nomor2.setHorizontalAlignment(SwingConstants.CENTER);
		
		counter3.setHorizontalAlignment(SwingConstants.CENTER);
		//nomor3.setHorizontalAlignment(SwingConstants.CENTER);
		
		counter4.setHorizontalAlignment(SwingConstants.CENTER);
		//nomor4.setHorizontalAlignment(SwingConstants.CENTER);
		
		counter5.setHorizontalAlignment(SwingConstants.CENTER);
		//nomor5.setHorizontalAlignment(SwingConstants.CENTER);
		
		counter6.setHorizontalAlignment(SwingConstants.CENTER);
		//nomor6.setHorizontalAlignment(SwingConstants.CENTER);
		
		counter7.setHorizontalAlignment(SwingConstants.CENTER);
		//nomor7.setHorizontalAlignment(SwingConstants.CENTER);
		
		counter8.setHorizontalAlignment(SwingConstants.CENTER);
		counter9.setHorizontalAlignment(SwingConstants.CENTER);
		counter10.setHorizontalAlignment(SwingConstants.CENTER);
		//nomor8.setHorizontalAlignment(SwingConstants.RIGHT);
		/*
		sell1.setHorizontalAlignment(SwingConstants.RIGHT);
		buy1.setHorizontalAlignment(SwingConstants.RIGHT);
		
		sell2.setHorizontalAlignment(SwingConstants.RIGHT);
		buy2.setHorizontalAlignment(SwingConstants.RIGHT);
		
		sell3.setHorizontalAlignment(SwingConstants.RIGHT);
		buy3.setHorizontalAlignment(SwingConstants.RIGHT);
		
		sell4.setHorizontalAlignment(SwingConstants.RIGHT);
		buy4.setHorizontalAlignment(SwingConstants.RIGHT);
		
		sell5.setHorizontalAlignment(SwingConstants.RIGHT);
		buy5.setHorizontalAlignment(SwingConstants.RIGHT);
		
		sell6.setHorizontalAlignment(SwingConstants.RIGHT);
		buy6.setHorizontalAlignment(SwingConstants.RIGHT);
		
		sell7.setHorizontalAlignment(SwingConstants.RIGHT);
		buy7.setHorizontalAlignment(SwingConstants.RIGHT);
		
		sell8.setHorizontalAlignment(SwingConstants.RIGHT);
		buy8.setHorizontalAlignment(SwingConstants.RIGHT);
		*/
		/*
		bln1.setHorizontalAlignment(SwingConstants.RIGHT);
		bln2.setHorizontalAlignment(SwingConstants.RIGHT);
		bln3.setHorizontalAlignment(SwingConstants.RIGHT);
		bln4.setHorizontalAlignment(SwingConstants.RIGHT);
		bln5.setHorizontalAlignment(SwingConstants.RIGHT);
		bba.setHorizontalAlignment(SwingConstants.RIGHT);
		kesra.setHorizontalAlignment(SwingConstants.RIGHT);
		tabunganku.setHorizontalAlignment(SwingConstants.RIGHT);
		*/
		
		//clear all content of counter and nomor.
		counter1.setText("000");
		counter2.setText("000");
		counter3.setText("000");
		counter4.setText("000");
		counter5.setText("000");
		counter6.setText("000");
		counter7.setText("000");
		counter8.setText("000");
		counter9.setText("000");
		/*
		nomor1.setText("");
		nomor2.setText("");
		nomor3.setText("");
		nomor4.setText("");
		nomor5.setText("");
		nomor6.setText("");
		nomor7.setText("");
		*/
		try {
			ReadConfig.getInstance(null);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//media.add(new VideoPanel("video/1.mpg"));
		SwingUtilities.invokeLater(new Runnable(){
			public void run()
			{
				String vol=ReadConfig.GET("VOLUME");
				float volume = Float.parseFloat(vol==null ? "1.0" : vol);
				media_video=Integer.parseInt(ReadConfig.GET("MEDIA_VIDEO"));
				if(media_video==1)
				{
					vp=new VideoPanel(volume);
				}
				else if(media_video==0)
				{
					vp=new ImagePanel();
				}
				else if(media_video==2)
				{
					vp=new DVDPanel();
				}
				else
					vp=new DVDMovie();
				
				int iWidth=Integer.parseInt(ReadConfig.GET("VIDEO_WIDTH"));
				int iHeight=Integer.parseInt(ReadConfig.GET("VIDEO_HEIGHT"));
				pp.setPreferredSize(new Dimension(iWidth,iHeight));
				vp.setPreferredSize(new Dimension(iWidth,iHeight));
				media.add(vp);		
			}
			
		});
	}
	
	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		UIManager.setLookAndFeel("com.jtattoo.plaf.noire.NoireLookAndFeel");
		new LCDSQ();
	}
	public void keyTyped(KeyEvent arg0) {
		// TODO Auto-generated method stub
		
	}
	public void keyPressed(KeyEvent arg0) {
		// TODO Auto-generated method stub
		
	}
	public void keyReleased(KeyEvent arg0) {
		// TODO Auto-generated method stub
		if(arg0.getKeyCode()==KeyEvent.VK_ESCAPE)
		{
			lcdEng.stopListening();
			lcdEng=null;
			isAlive=false;
			ledTicker.stopAnimation();
			frame.setVisible(false);
			frame.dispose();
			frame=null;
		}
	}
	private void showTime()
	{
		SimpleDateFormat sdf = new SimpleDateFormat("EEE dd/MM/yyyy HH:mm:ss");
		Calendar cal = Calendar.getInstance();
		int hour = cal.get(Calendar.HOUR);
		cal.set(Calendar.HOUR,hour);
		date.setText(sdf.format(cal.getTime()));
		//date1.setText(sdf.format(cal.getTime()));
	}
	
	class TimerTask extends Thread
	{
		public TimerTask()
		{
			
		}
		
		public void run()
		{
			while(isAlive)
			{
				showTime();
				try {
					Thread.sleep(1000L);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
				}
			}
		}
	}

	public void recv(String data) {
		// TODO Auto-generated method stub
		System.out.println("recv: " + data);
		parse(data);
	}
	
	private void parse(String parsed)
	{
		String[] arrParse = parsed.split("\\|");
		if(arrParse[0].equals("A"))
		{
			//berarti mengirimkan antrian
			DecimalFormat dec = new DecimalFormat("0");
			receiveQueue(dec.format(Integer.parseInt(arrParse[1])),arrParse[2]);
		}
		else if(arrParse[0].equals("B"))
			receiveText(arrParse[1]);
		else
		{
			counter1.setText("000");
			counter2.setText("000");
			counter3.setText("000");
			counter4.setText("000");
			counter5.setText("000");
			counter6.setText("000");
			counter7.setText("000");
			counter8.setText("000");
			counter9.setText("000");
			counter10.setText("000");
		}
	}
	
	private void receiveText(String text)
	{
		TextTickerElement ste = (TextTickerElement)elements.get("1");
		ste.setText(text);
		ledTicker.update(ste);
	}
	
	private void receiveQueue(String counter,String queue)
	{
		if(counter.equals("1"))
			counter1.setText(queue);
		if(counter.equals("2"))
			counter2.setText(queue);
		if(counter.equals("3"))
			counter3.setText(queue);
		if(counter.equals("4"))
			counter4.setText(queue);
		if(counter.equals("5"))
			counter5.setText(queue);
		if(counter.equals("6"))
			counter6.setText(queue);
		if(counter.equals("7"))
			counter7.setText(queue);
		if(counter.equals("8"))
			counter8.setText(queue);
		if(counter.equals("9"))
			counter9.setText(queue);
		if(counter.equals("10"))
			counter10.setText(queue);
	}

	public void windowOpened(WindowEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	public void windowClosing(WindowEvent arg0) {
		// TODO Auto-generated method stub
		m_isStop=true;
		if(vp!=null)
		{
			if (media_video==1)
				((VideoPanel)vp).save();
			else if(media_video==0)
				((ImagePanel)vp).stop();
			else if(media_video==2)
				((DVDPanel)vp).stopPlay();
		}
	}

	public void windowClosed(WindowEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	public void windowIconified(WindowEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	public void windowDeiconified(WindowEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	public void windowActivated(WindowEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	public void windowDeactivated(WindowEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void updateKurs(String[] datas,int idx) {
		// TODO Auto-generated method stub
		switch(idx)
		{
		case 0:
			kurs1.setText(datas[0]);
			sell1.setText(datas[1]);
			buy1.setText(datas[2]);
			break;
		case 1:
			kurs2.setText(datas[0]);
			sell2.setText(datas[1]);
			buy2.setText(datas[2]);
			break;
		case 2:
			kurs3.setText(datas[0]);
			sell3.setText(datas[1]);
			buy3.setText(datas[2]);
			break;
		case 3:
			kurs4.setText(datas[0]);
			sell4.setText(datas[1]);
			buy4.setText(datas[2]);
			break;
		case 4:
			kurs5.setText(datas[0]);
			sell5.setText(datas[1]);
			buy5.setText(datas[2]);
			break;
		case 5:
			kurs6.setText(datas[0]);
			sell6.setText(datas[1]);
			buy6.setText(datas[2]);
			break;
		case 6:
			kurs7.setText(datas[0]);
			sell7.setText(datas[1]);
			buy7.setText(datas[2]);
			break;
		case 7:
			kurs8.setText(datas[0]);
			sell8.setText(datas[1]);
			buy8.setText(datas[2]);
			break;
		}
	}

	@Override
	public boolean isStop() {
		// TODO Auto-generated method stub
		return m_isStop;
	}

	@Override
	public void updateSukuBunga(String datas, int idx) {
		// TODO Auto-generated method stub
		String[] items = datas.split("\\|");
		switch(idx)
		{
		case 0:
			idbln1.setText(items[0]);
			bln1.setText(items[1]);
			bln1usd.setText(items[2]);
			break;
		case 1:
			idbln2.setText(items[0]);
			bln2.setText(items[1]);
			bln2usd.setText(items[2]);
			break;
		case 2:
			idbln3.setText(items[0]);
			bln3.setText(items[1]);
			bln3usd.setText(items[2]);
			break;
		case 3:
			idbln4.setText(items[0]);
			bln4.setText(items[1]);
			bln4usd.setText(items[2]);
			break;
		case 4:
			idtabungan1.setText(items[0]);
			tabungan1.setText(items[1]);
			tabungan1_1.setText(items[2]);
			break;
		case 5:
			idtabungan2.setText(items[0]);
			tabungan2.setText(items[1]);
			tabungan2_1.setText(items[2]);	
			break;
		case 6:
			idtabungan3.setText(items[0]);
			tabungan3.setText(items[1]);
			tabungan3_1.setText(items[2]);
			break;
		case 7:
			idtabungan4.setText(items[0]);
			tabungan4.setText(items[1]);
			tabungan4_1.setText(items[2]);
			break;
		case 8:
			idtabungan5.setText(items[0]);
			tabungan5.setText(items[1]);
			tabungan5_1.setText(items[2]);
			break;
		case 9:
			tabunganusd.setText(items[1]);
			tabunganusd_1.setText(items[2]);
			break;
		case 10:
			tabunganku.setText(items[1]);
			tabunganku_1.setText(items[2]);
			break;
		}
	}
}
